import { Image, InfiniteScroll, List } from 'antd-mobile'
// mock数据
// import { users } from './users'
import { useEffect, useState } from 'react'
import { ListRes, fetchListAPI } from '@/apis/list'
import { useNavigate } from 'react-router-dom'

type props = {
  channelId: string | '0'
}
const HomeList = (props: props) => {
  const { channelId } = props
  const [listRes, setListRes] = useState<ListRes>({
    results: [],
    pre_timestamp: '' + new Date().getTime(),
  })
  useEffect(() => {
    const getList = async () => {
      try {
        const res = await fetchListAPI({
          channel_id: channelId,
          timestamp: '' + new Date().getTime(),
        })
        // console.log(res)
        setListRes({
          results: res.data.data.results,
          pre_timestamp: listRes.pre_timestamp,
        })
      } catch (error) {
        console.error(error)
        throw new Error('请求失败')
      }
    }
    getList()
  }, [channelId])
  // console.log(listRes)
  // 标志当前是否还有新数据
  // 上拉加载的触发必须条件1. hasMore true 2.小于 threshold
  const [hasMore, setHasMore] = useState(true)
  // 加载下一页的函数
  const loadMore = async () => {
    // 编写加载下一页的核心逻辑
    console.log('加载下一页')

    try {
      const res = await fetchListAPI({
        channel_id: channelId,
        timestamp: listRes.pre_timestamp,
      })
      // console.log(res)
      // 拼接新数据 + 存取下一次请求的时间戳
      setListRes({
        results: [...listRes.results, ...res.data.data.results],
        pre_timestamp: res.data.data.pre_timestamp,
      })
      // 停止监听
      if (res.data.data.results.length === 0) {
        setHasMore(false)
      }
    } catch (error) {
      console.error(error)
      throw new Error('请求失败')
    }

    // setHasMore(false)
  }
  // 路由跳转
  const navigetion = useNavigate()
  const goToDetail = (id: string) => {
    // 路由跳转
    navigetion(`./detail?id=${id}`)
  }
  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item onClick={() => goToDetail(item.art_id)} key={item.art_id} prefix={<Image src={item.cover?.images?.[0]} style={{ borderRadius: 20 }} fit="cover" width={40} height={40} />} description={item.pubdate}>
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={30} />
    </>
  )
}

export default HomeList
